package com.huiminpay.transaction.message;

import com.alibaba.fastjson.JSON;
import com.huiminpay.paymentagent.api.dto.PaymentResponseDTO;
import com.huiminpay.paymentagent.api.dto.TradeStatus;
import com.huiminpay.transaction.api.TransactionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * ClassName:TransactionPayConsumer
 * Package:com.huiminpay.transaction.message
 * Time: 2024/8/1
 */
@Component
@Slf4j
@RocketMQMessageListener(topic = "TP_PAYMENT_RESULT",consumerGroup = "CID_ORDER_CONSUMER")
public class TransactionPayConsumer implements RocketMQListener<MessageExt> {
    @Resource
    TransactionService transactionService;

    /**
     * 当收到消息时触发的方法
     *
     * @param messageExt 消息对象
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        // 获取消息体
        byte[] body = messageExt.getBody();
        // 将消息体转换为字符串
        String jsonString = new String(body);
        // 打印日志，记录接收到的支付结果消息
        log.info("交易服务接收到支付结果消息：{}", JSON.toJSONString(jsonString));
        //接收到消息，内容包括订单状态
        PaymentResponseDTO responseDTO = JSON.parseObject(jsonString, PaymentResponseDTO.class);
        String tradeNo = responseDTO.getTradeNo(); // 获取交易订单号
        String outTradeNo = responseDTO.getOutTradeNo(); // 获取商户订单号
        //订单状态
        TradeStatus tradeState = responseDTO.getTradeState();

        //更新数据库订单表
        switch (tradeState) {
            case SUCCESS:
                // 更新订单状态为已支付
                transactionService.updateOrderTradeNoAndTradeState(outTradeNo,tradeNo,"2");
                return;
            case REVOKED:
                //关闭
                transactionService.updateOrderTradeNoAndTradeState(outTradeNo,tradeNo,"4");
                return;
            case FAILED:
                //失败
                transactionService.updateOrderTradeNoAndTradeState(outTradeNo,tradeNo,"5");
                return;
            default:
                throw new RuntimeException(String.format("无法解析支付结果：%s",body));
        }

    }

}
